package com.lagou.rpc.register.handler;

import com.lagou.rpc.common.ConfigKeeper;
import com.lagou.rpc.common.registry.RpcRegistryHandler;
import com.lagou.rpc.register.handler.impl.ZookeeperRegistryHandler;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Service;

/**
 * 注册中心工厂类
 * 注意这种设计思路，工厂模式
 */
@Service
public class RpcRegistryFactory implements FactoryBean<RpcRegistryHandler>, DisposableBean {

    private RpcRegistryHandler rpcRegistryHandler;

    @Override
    public RpcRegistryHandler getObject() throws Exception {
       if (null != rpcRegistryHandler) {
           return rpcRegistryHandler;
       }
       rpcRegistryHandler = new ZookeeperRegistryHandler(ConfigKeeper.getInstance().getZkAddr());
       return rpcRegistryHandler;
    }

    @Override
    public Class<?> getObjectType() {
        return rpcRegistryHandler.getClass();
    }

    @Override
    public void destroy() throws Exception {
        if(null != rpcRegistryHandler) {
            rpcRegistryHandler.destroy();
        }
    }
}
